<?php

namespace App\Events;

use App\Constant\JpushCode;
use Illuminate\Queue\SerializesModels;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Broadcasting\InteractsWithSockets;
use MathPHP\Exception\BadParameterException;

class JpushNoticeEvent
{
    use Dispatchable, InteractsWithSockets, SerializesModels;

    /**
     * @var array
     */
    public $notification; //通知栏消息

    // +----------------------------------------------------------------------
    // eg.
    //        event(new JpushNoticeEvent([
    //            'body' => '这是一个自定义body数据', //消息体
    //            'title' => '这是一个自定义title', //消息标题
    //            /**
    //             * 1 所有用户
    //             * 2 relationId 关联用户
    //             * 3 tag 关联标签用户
    //             */
    //            'audience' => JpushCode::AUDIENCE_TYPE_ONE, //消息通知目标方式
    //            /**
    //             * audience = 1 可不传
    //             *          = 2 从user_globals表中获取relationId [relationId1,relationId2,...]
    //             *          = 3 获取tag  [tag1,tag2,...]
    //             */
    //            'to' => [], //消息通知具体用户
    //            /**
    //             * jump_type = 1 跳转首页
    //             *           = 2 跳转借款记录页面
    //             */
    //            'extras' => [
    //                'jump_type' => 1,
    //            ] //自定义额外参数
    //        ]));
    // +----------------------------------------------------------------------

    /**
     * JpushQueueEvent constructor.
     * @param array $notification 通知栏数据
     * @throws BadParameterException
     */
    public function __construct($notification)
    {
        /**
         * 通知栏消息
         */
        if (!isset($notification['title']) || empty($notification['title']))
            $notification['title'] = '通知栏通知';
        if (!isset($notification['body']) || empty($notification['body']))
            throw new BadParameterException('缺少极推body');
        if (!isset($notification['extras']) || empty($notification['extras']))
            $notification['extras']['jump_type'] = JpushCode::EXTRAS_JUMP_TYPE_ONE;
        if (!is_array($notification['extras']) || count($notification['extras']) != count($notification['extras'], 1))
            throw new BadParameterException('极推extras不符合规定');
        if (!isset($notification['audience']) || !in_array($notification['audience'], [
                JpushCode::AUDIENCE_TYPE_ONE,
                JpushCode::AUDIENCE_TYPE_TWO,
                JpushCode::AUDIENCE_TYPE_THREE,
        ])) {
            throw new BadParameterException('极推audience不符合规定');
        }
        if (JpushCode::AUDIENCE_TYPE_ONE != $notification['audience'] && (empty($notification['to']) || !is_array($notification['to'])))
            throw new BadParameterException('极推to不符合规定');
        $this->notification = $notification;
    }
}